package com.dodayum.controller;

import com.dodayum.entity.FileEntity;
import com.dodayum.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    FileService fileService;

    @PostMapping("/save")
    public ResponseEntity<Object> saveFile(@RequestParam(value = "file") MultipartFile multipartFile,
                           @RequestParam(value = "remark", required = false) String remark) throws Exception {

        long startTime = System.currentTimeMillis();
        fileService.save(multipartFile,remark);
        long endTime = System.currentTimeMillis();
        long timeElapsed = endTime - startTime; // 时间差，单位是毫秒
        return ResponseEntity.ok().body("文件"+multipartFile.getOriginalFilename()+"导入完成，共耗时"+timeElapsed / 1000+"秒");
    }

    @GetMapping("/get")
    public ResponseEntity<Object> getFileById(@RequestParam("id") Long id) throws Exception {
        FileEntity info = fileService.getInfoById(id);
        if (ObjectUtils.isEmpty(info)){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("根据id没找到文件");
        }
        byte[] fileById = fileService.getFileById(id);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", info.getName());
        return ResponseEntity.ok()
                .headers(headers)
                .body(fileById);
    }

    @DeleteMapping("/delete")
    public void deleteFileById(@RequestParam("id") Long id) throws Exception {
        fileService.deleteById(id);
    }

    @DeleteMapping("/delete/all")
    private void deleteFileByIds() throws Exception {
        fileService.deleteFileByIds();
    }

}
